package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 热点评论处理
     *
     * @param apComment 评论对象
     */
    @Override
    @Async("taskExecutor") //异步执行
    public void hotCommentExecutor(ApComment apComment) {
        log.info("热点文章计算开始===============================");
        //判断点赞数量是否大于10
        if (apComment.getLikes() >= 10) {
            //查询当前文章下的所有热点评论集合

            Query query = Query.query(Criteria.where("articleId").is(apComment.getArticleId())
                            //热点评论需要按照点赞数倒序排序
                            .and("flag").is((short) 1))
                    .with(Sort.by(Sort.Direction.DESC, "likes"));
            //查询出数据
            List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
            //判断当前集合是否为空
            if (apComments == null || apComments.size() < 5) {
                //如果为空或者小于5则将评论改为热评
                apComment.setFlag((short) 1);
                //保存修改
                mongoTemplate.save(apComment);
            }

            //如果集合的长度大于等于5时,获取点赞数量最少的评论
            if (apComments.size() >= 5) {
                query.skip(5L);
                //查询满足条件的评论

                List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
                //判断查询到的集合是否为null
                if (commentList != null) {
                    for (ApComment comment : commentList) {
                        comment.setFlag((short) 0);
                        //保存修改
                        mongoTemplate.save(comment);
                    }
                }
            }

            //不超过的部分,和当前点赞数量做对比  谁的点赞数量多改为热评
            ApComment comment = apComments.get(4);
            if (comment.getLikes() < apComment.getLikes()) {
                //保存修改
                apComment.setFlag((short) 1);
                mongoTemplate.save(apComment);
                //保存修改
                comment.setFlag((short) 0);
                mongoTemplate.save(comment);
            }
        }
        log.info("热点文章计算结束===============================");
    }
}